#include <stdio.h>
#include <linux/fb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "bmp.h"
#include "oled.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
#include <ifaddrs.h>

#define IF_NAME "wlan0"

void getNowtime(char *mytime_t, char *mydate_t) 
{
    time_t current_time;
    struct tm* now_time;

    time(&current_time);
    now_time = localtime(&current_time);
	strftime(mydate_t, 15, "%F ", now_time);
    strftime(mytime_t, 10, "%T", now_time);
}


int get_local_ip(char * ifname, char *ip)
{
    char *temp = NULL;
    int inet_sock;
    struct ifreq ifr;

    inet_sock = socket(AF_INET, SOCK_DGRAM, 0); 

    memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
    memcpy(ifr.ifr_name, ifname, strlen(ifname));

    if(0 != ioctl(inet_sock, SIOCGIFADDR, &ifr)) 
    {   
        perror("ioctl error");
        return -1;
    }

    temp = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);     
    memcpy(ip, temp,15);

    close(inet_sock);

    return 0;
}


char str[15];
char mytime[8],mydate[15];


int main(int argc,char *argv[])
{
	if(argc!=2)
	{
		printf("格式: %s </dev/fbx>\n",argv[0]);
		return 0;
	}
	
	OLED_Init(argv[1]);
	get_local_ip(IF_NAME,str);
	while(1)
	{	
		OLED_ShowString(0,0,"IP:",16,1);
		OLED_ShowString(24,0,str,16,1);
		getNowtime(mytime,mydate);
		OLED_ShowString(0,16,mytime,32,1);
		OLED_ShowString(0,48,mydate,16,1);
		sleep(1);
	}
	unmap();
	return 0;
}

